class SettingsManager {
    constructor() {
        this.init();
    }

    init() {
        this.loadSettings();
        this.setupSettingsListeners();
    }

    loadSettings() {
        // 从localStorage加载设置
        const settings = JSON.parse(localStorage.getItem('todoSettings') || '{}');

        // 应用设置到UI
        Object.keys(settings).forEach(key => {
            const element = document.getElementById(key);
            if (element && element.type === 'checkbox') {
                element.checked = settings[key];
            }
        });
    }

    saveSettings() {
        // 收集所有设置
        const settings = {};
        document.querySelectorAll('.settings-main input[type="checkbox"]').forEach(input => {
            settings[input.id] = input.checked;
        });

        // 保存到localStorage
        localStorage.setItem('todoSettings', JSON.stringify(settings));
    }

    setupSettingsListeners() {
        // 监听所有设置项的变更
        document.querySelectorAll('.settings-main input[type="checkbox"]').forEach(input => {
            input.addEventListener('change', () => {
                this.saveSettings();
                this.applySettings();
            });
        });
    }

    applySettings() {
        // 根据设置更新UI显示
        const settings = JSON.parse(localStorage.getItem('todoSettings') || '{}');

        // 基础导航项的显示/隐藏
        this.toggleNavItem('today', settings.todayTasks);
        this.toggleNavItem('tomorrow', settings.tomorrowTasks);
        this.toggleNavItem('week', settings.weekTasks);
        this.toggleNavItem('planned', settings.plannedTasks);
        this.toggleNavItem('completed', settings.completedTasks);
        this.toggleNavItem('tasks', settings.allTasks);

        // 优先级分组的显示/隐藏
        const prioritySection = document.getElementById('prioritySection');
        if (settings.showPrioritySection === false) {
            prioritySection.style.display = 'none';
        } else {
            prioritySection.style.display = 'block';
            this.toggleNavItem('high-priority', settings.highPriorityTasks);
            this.toggleNavItem('medium-priority', settings.mediumPriorityTasks);
            this.toggleNavItem('low-priority', settings.lowPriorityTasks);
        }
    }

    toggleNavItem(category, show) {
        const element = document.querySelector(`[data-category="${category}"]`);
        if (element) {
            element.style.display = show === false ? 'none' : 'flex';
        }
    }
}

module.exports = SettingsManager;